package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 


import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.RsaDecrypt;
import com.ld.hpfs.dao.UtilMapper;
import com.ld.hpfs.pojo.CompanyDetail;
import com.ld.hpfs.pojo.Company;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.ExtReturn;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.CompanyService;
import com.ld.hpfs.service.HistoryService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class CompanyController
{
    private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);
    @Autowired
    private CompanyService      companyService;
    @Autowired
    private UtilMapper          utilMapper;

    //用于添加history表
    @Autowired
    private HistoryService          historyService;

    @RequestMapping(value = "/addcompany")
    @ResponseBody
    public Object addCompany(@RequestParam String companycode, @RequestParam String companyname,
            @RequestParam String companyaddress, @RequestParam String companycity, @RequestParam String companypostcode,
            @RequestParam String companyrule, @RequestParam String companyorgcode, @RequestParam String accountmanager, @RequestParam String operator,
            @RequestParam String checker, @RequestParam String hasledger,@RequestParam String archiveInvoice,@RequestParam String applyExpress,@RequestParam String cpn_id,  @RequestParam int pid, 
            HttpSession session, HttpServletRequest request)
    {
    	System.out.println("save");
        User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
        if (user == null)
        {
            return new ExtReturn(false, "未登陆。");
        }

        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
        int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
        //int creatorId = utilMapper.getCreatorIdFromGroupId(groupId);
        

        CompanyDetail detail = new CompanyDetail();
        detail.setAccountmanager(accountmanager);
        detail.setChecker(checker);
        detail.setCompanyaddress(companyaddress);
        detail.setCompanycity(companycity);
        detail.setCompanycode(companycode);
        detail.setCompanyname(companyname);
        detail.setCompanyorgcode(companyorgcode);
        detail.setCompanypostcode(companypostcode);
        detail.setCompanyrule(companyrule);
        detail.setCreatorid(Integer.parseInt(user.getUserId()));
        detail.setGroupId(groupId);
        detail.setOperator(operator);
        detail.setHasledger(hasledger);
        detail.setArchiveInvoice(archiveInvoice);
        detail.setApplyExpress(applyExpress);
        if (cpn_id != "") {
        	detail.setCpn_id(Integer.parseInt(cpn_id));
        }
      //  detail.setIgnoreBalanceChk(ignore_balance_chk);
        detail.setOperator(operator);
        detail.setPid(pid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// format.setTimeZone(TimeZone.getTimeZone( "GMT-0"));
		String date = format.format(new Date());
		detail.setCreatetime(date);
		int checkName = companyService.checkCompanyName(detail);
		if(checkName == -1){
		int iResult = companyService.addCompany(detail);
		}else{
			return new ExtReturn(false, "同样名称或代码的公司已经存在。");
		}
        return new ExtReturn(true, "success");
    }

    @RequestMapping(value = "/deleteCompanies")
    @ResponseBody
    public Object deleteCompanies(@RequestParam String ids, HttpSession session, HttpServletRequest request)
    {

        User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
        if (user == null)
        {
            return new ExtReturn(false, "未登陆。");
        }

        // 此方法报错 可能是数据原因groupid为64 导致第三部creatorId查询结果为空报错 故注释掉此方法 By张
//        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
//        int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
//        int creatorId = utilMapper.getCreatorIdFromGroupId(groupId);

        if (ids != null && ids.length() > 0)
        {
            StringTokenizer st = new StringTokenizer(ids, "|");
            String[] idlist = new String[st.countTokens()];

            int i = 0;
            while (st.hasMoreTokens())
            {
                idlist[i++] = st.nextToken();
            }
            for (i = 0; i < idlist.length; i++)
            {
            	int check = companyService.checkIsParent(Integer.parseInt(idlist[i]));
            	if(check == 0 ){
            		int check1 = companyService.checkHaveData(Integer.parseInt(idlist[i]));
            		if(check1 == 0){
            			
            			// 用于添加history表
            			HashMap<String, Object> param = new HashMap<String, Object>();
            			param.put("id", Integer.parseInt(idlist[i]));
                		param.put("update_id", Integer.parseInt(user.getUserId()));
        				param.put("update_name", user.getAccount());
        				historyService.addCompanyHistory(param, false);
            			
        				// 用于更改红废审核者
        				HashMap<String, Object> AbandonChecker = new HashMap<String, Object>();
        				AbandonChecker.put("createid", Integer.parseInt(user.getUserId()));
        				AbandonChecker.put("cid", Integer.parseInt(idlist[i]));
        				AbandonChecker.put("firstchecker", "");
        				AbandonChecker.put("secondchecker", "");
        				companyService.updateChecker(AbandonChecker);
        				
            			companyService.deleteCompany(Integer.parseInt(idlist[i]));
            		}else{
            			return new ExtReturn(false, "所选公司已有数据，不可删除。");
            		}
            	}else{
            		return new ExtReturn(false, "所选公司拥有子公司，不可删除。");
            	}
            }
        }

        return new ExtReturn(true, "success");
    }

    @RequestMapping(value = "/getCompanies")
    @ResponseBody
    public void getCompanies(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer)
    {
        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
        if (currentCompany == null)
        {
            return;
        }
        
        int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));

        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("groupid", groupId);
        
        List<Company> companies = companyService.getCompanies(param);
        int count = param.get("pageCount") == null ? 0 : Integer.parseInt(param.get("pageCount").toString());
        response.setContentType("text/plain;charset=UTF-8");
        String resultstring = formatCompanyResults(companies, count);
        logger.debug("{}", resultstring);
        writer.print(resultstring);
    }

    private String formatCompanyResults(List<Company> companies, int count)
    {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\r\n");
        sb.append("\"success\": true,");
        //sb.append("\r\n");
        //sb.append("\"total\":").append(count).append(",");
        sb.append("\r\n");
        sb.append("\"children\": [");
        sb.append("\r\n");
        if (companies != null)
        {
            for (int i = 0; i < companies.size(); i++)
            {
                Company company = companies.get(i);
                String strCompany = formatCompany(company); 
                sb.append(strCompany);
                if (i < companies.size() - 1)
                {
                    sb.append(",");
                }
                sb.append("\r\n");
            }
        }
        sb.append("]");
        sb.append("\r\n");
        sb.append("}");

        try
        {
            return sb.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return "";
    }
    
    String formatCompany(Company company)
    {
    	StringBuilder sb = new StringBuilder();
    	sb.append("{");
    	sb.append("\"id\":").append(company.getId()).append(",");
    	sb.append("\"text\":\"").append(company.getCompanyname()).append("\",");
		sb.append("\"iconCls\" : \"tj-tree-file\", ");
    	if (company.getChildren() == null || company.getChildren().size() == 0)
    	{
    		sb.append("\"leaf\":true");
    	}else
    	{
    		sb.append("\"leaf\":false,");
    		sb.append("\"expanded\" : true, ");
    		sb.append("\"children\":").append("[");
    		
    		for(int i=0; i<company.getChildren().size(); i++)
    		{
    			String strChild = formatCompany(company.getChildren().get(i));
    			sb.append(strChild);
    			if (i < company.getChildren().size()-1)
    			{
    				sb.append(",");
    			}
    		}
    		
    		sb.append("]");
    	}
    	
    	sb.append("}");
    	
    	return sb.toString();
    }
    
    String formatCompany(CompanyDetail detail)
    {
    	 StringBuffer sb = new StringBuffer();
         sb.append("{");
         sb.append("\r\n");
         sb.append("\"success\": true,");
         //sb.append("\r\n");
         //sb.append("\"total\":").append(count).append(",");
         sb.append("\r\n");
         sb.append("\"children\":[");
         sb.append("\r\n");
       //  '','','','','','','','','',''
         sb.append("{");
         sb.append("pid:\"").append(detail.getPid()).append("\",");
         sb.append("companycode:\"").append(detail.getCompanycode()).append("\",");
         sb.append("companyname:\"").append(detail.getCompanyname()).append("\",");
         sb.append("companyaddress:\"").append(detail.getCompanyaddress()).append("\",");
         sb.append("companycity:\"").append(detail.getCompanycity()).append("\",");
         sb.append("companypostcode:\"").append(detail.getCompanypostcode()).append("\",");
         sb.append("companyrule:\"").append(detail.getCompanyrule()).append("\",");
         sb.append("companyorgcode:\"").append(detail.getCompanyorgcode()).append("\",");
         sb.append("accountmanager:\"").append(detail.getAccountmanager()).append("\",");
         sb.append("operator:\"").append(detail.getOperator()).append("\",");
         sb.append("checker:\"").append(detail.getChecker()).append("\",");
         sb.append("hasledger:\"").append(detail.getHasledger()).append("\",");
         sb.append("archiveInvoice:\"").append(detail.getArchiveInvoice()).append("\",");
         sb.append("applyExpress:\"").append(detail.getApplyExpress()).append("\",");
         sb.append("cpn_id:\"").append(detail.getCpn_id()).append("\",");
         sb.append("firstchecker:\"").append(detail.getFirstchecker()).append("\",");
         sb.append("secondchecker:\"").append(detail.getSecondchecker()).append("\",");
     //    sb.append("ignore_balance_chk:\"").append(detail.getIgnoreBalanceChk()).append("\"");
         
         sb.append("}");
                  
         sb.append("]");
         sb.append("\r\n");
         sb.append("}");

         try
         {
             return sb.toString();
         }
         catch (Exception e)
         {
             e.printStackTrace();
         }
         return "";
    }
    
    @RequestMapping(value = "/getCompanyDetail")
    @ResponseBody
    public void updateCompany(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer)
    {
    	 String id = request.getParameter("id");
    	 if (id == null || id.isEmpty()) return;
    	 CompanyDetail detail = companyService.getCompany(Integer.parseInt(id));        
    	 response.setContentType("text/plain;charset=UTF-8");
    	 String resultstring = JackJson.fromObjectToJson(detail);
//         String resultstring = formatCompany(detail);
         logger.debug("{}", resultstring);
         writer.print(resultstring);
    }

    @RequestMapping(value = "/updateCompany")
    @ResponseBody
    public Object updateCompany(@RequestParam String companycode, @RequestParam String companyname,
            @RequestParam String companyaddress, @RequestParam String companycity, @RequestParam String companypostcode,
            @RequestParam String companyrule, @RequestParam String companyorgcode, @RequestParam String accountmanager, @RequestParam String operator,
            @RequestParam String checker, @RequestParam String hasledger, @RequestParam String archiveInvoice,@RequestParam String applyExpress,@RequestParam String cpn_id,   
            @RequestParam String id,@RequestParam int pid, @RequestParam String firstchecker,@RequestParam String secondchecker,
            HttpSession session, HttpServletRequest request)
    {
        User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
        if (user == null)
        {
            return new ExtReturn(false, "未登陆。");
        }

        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
        int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
       // int creatorId = utilMapper.getCreatorIdFromGroupId(groupId);
        CompanyDetail detail = new CompanyDetail();
        detail.setAccountmanager(accountmanager);
        detail.setChecker(checker);
        detail.setCompanyaddress(companyaddress);
        detail.setCompanycity(companycity);
        detail.setCompanycode(companycode);
        detail.setCompanyname(companyname);
        detail.setCompanyorgcode(companyorgcode);
        detail.setCompanypostcode(companypostcode);
        detail.setCompanyrule(companyrule);
        detail.setCreatorid(Integer.parseInt(user.getUserId()));
        detail.setOperator(operator);
        detail.setGroupId(groupId);
        detail.setHasledger(hasledger);
        detail.setArchiveInvoice(archiveInvoice);
        detail.setApplyExpress(applyExpress);
        detail.setCpn_id(Integer.parseInt(cpn_id));
     //  detail.setIgnoreBalanceChk(ignore_balance_chk);
        detail.setCompanyId(Integer.parseInt(id));
        detail.setPid(pid);
        
        int checkName = companyService.checkCompanyName(detail);
		if((checkName == Integer.parseInt(id)) || (checkName == -1)){
			
			// 用于添加history表
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("id", Integer.parseInt(id));
    		param.put("update_id", Integer.parseInt(user.getUserId()));
			param.put("update_name", user.getAccount());
			historyService.addCompanyHistory(param, true);
			
			// 用于更改红废审核者
			HashMap<String, Object> AbandonChecker = new HashMap<String, Object>();
			AbandonChecker.put("createid", Integer.parseInt(user.getUserId()));
			AbandonChecker.put("cid", Integer.parseInt(id));
			AbandonChecker.put("firstchecker", firstchecker);
			AbandonChecker.put("secondchecker", secondchecker);
			companyService.updateChecker(AbandonChecker);
			
			int iResult = companyService.updateCompany(detail);
		}
        return new ExtReturn(true, "success");
    }
    
    @RequestMapping(value = "/getParentCompanyList",method = RequestMethod.GET)
    @ResponseBody
    public void getParentCompanyList(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer)
    {
    	 String id = (String)request.getParameter("id") == null ? "0" : (String)request.getParameter("id");
        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
        if (currentCompany == null)
        {
            return;
        }       
        response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
			HashMap<String, Object> param = new HashMap<String, Object>();		
	        param.put("id", Integer.parseInt(id));	     
			ArrayList<HashMap<String,Object>> result1 =companyService.getParentCompanyList(param);	
			HashMap<String,Object> e = new HashMap<String,Object>();
			String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
			e.put("COMPANY_HID",0);
			if(language.equals("zh_CN")){
				e.put("COMPANY_NAME","根公司");
			}else if(language.equals("en")){
				e.put("COMPANY_NAME","Root Company");
			}
			result.add(e);
			result.addAll(result1);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
    }
    
    /*
     * 判断公司数量是否超限
     */
    @RequestMapping(value = "/checkCompanyNumber")  
    @ResponseBody
    public void checkCompanyNumber(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer)
    {
    	try{
    		RsaDecrypt rsa = new RsaDecrypt();
    		HashMap<String,Object> result = new HashMap<String,Object>();
    		int companyNum = companyService.getCompanyNum();
    		String MaxCompany = rsa.Company_Number();
//    		Object maxCNum = session.getAttribute(WebConstants.MAX_COMPANY_NUMBER);
//    		if(maxCNum !=null){
    		if(MaxCompany !=null){
//    			int maxNum = Integer.parseInt(maxCNum.toString());
    			int maxNum = Integer.parseInt(MaxCompany.toString());
    			if(companyNum < maxNum){
    				result.put("resultcode",0);
    			}else{result.put("resultcode",9);}
    		}else{
    			result.put("resultcode",9);
    		}
    		writer.print(JackJson.fromObjectToJson(result));
    	}catch (Exception e){
    		logger.error("Exception: ", e);
    	}finally{
    		writer.flush();
			writer.close();
    	}
    }
    
    @RequestMapping(value = "/getUserList")
	public void geRoleList(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("cid", (String)request.getParameter("companyId"));
			ArrayList<HashMap<String,Object>> result =companyService.getUserList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
 
    /*
     * 检查是否启用发票归档功能
     */
    @RequestMapping(value = "/getArchiveInvoice")
    @ResponseBody
	public void getArchiveInvoice(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		try {
			
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			int result =companyService.getArchiveInvoice(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
    
    /*
     * 检查当前公司代码是否存在，若存在不可保存，弹出提示消息
     */
    @RequestMapping(value = "/isExistCompanyCode")
    @ResponseBody
	public void isExistCompanyCode(HttpSession session,HttpServletRequest request, HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		String companyCode = request.getParameter("companycode");
		String companyHid = request.getParameter("companyHid");
		String returnFlag = "true";
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			param.put("companyCode", companyCode);
			param.put("companyHid", companyHid);
			int result =companyService.isExistCompanyCode(param);
			HashMap<String,Object> currentCompanyCode =  companyService.getCurrentCompanyCode(param);
			if(result >= 1 && !(currentCompanyCode.get("COMPANY_CODE").equals(companyCode))){
				returnFlag = "false";
			}
	        logger.debug("{}", returnFlag);
	        writer.print(returnFlag);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
}
